package cn.itcast.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bean.Person;
import cn.itcast.service.PersonService;

@Transactional
public class PersonServiceBean implements PersonService {
	@Resource
	private SessionFactory sessionFactory;
	
	
	/* (non-Javadoc)
	 * @see cn.itcast.service.impl.PersonService#save(cn.itcast.bean.Person)
	 */
	public void save(Person person) {
		//得到当前被spring容器管理的session
		sessionFactory.getCurrentSession().persist(person);
	}
	
	/* (non-Javadoc)
	 * @see cn.itcast.service.impl.PersonService#update(cn.itcast.bean.Person)
	 */
	public void update(Person person) {
		sessionFactory.getCurrentSession().merge(person);
	}
	
	/* (non-Javadoc)
	 * @see cn.itcast.service.impl.PersonService#getPerson(int)
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Person getPerson(int personId) {
		
		return (Person)sessionFactory.getCurrentSession().get(Person.class, personId);
	}
	
	/* (non-Javadoc)
	 * @see cn.itcast.service.impl.PersonService#delete(int)
	 */
	public void delete(int personId) {
		sessionFactory.getCurrentSession().delete(
				sessionFactory.getCurrentSession().load(Person.class, personId)
		);
	}
	
	/* (non-Javadoc)
	 * @see cn.itcast.service.impl.PersonService#getPersons()
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@SuppressWarnings("unchecked")
	public List<Person> getPersons() {
		return sessionFactory.getCurrentSession().createQuery("from Person").list();
		
	}
}
